package com.zhouyibike.uu.ui.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;

import com.gyf.barlibrary.ImmersionBar;
import com.gyf.barlibrary.OnKeyboardListener;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.beta.UpgradeInfo;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.UpMSGResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.service.UpdateService;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.ui.view.CustomerDialog;
import com.zhouyibike.uu.utils.DataSingle;
import com.zhouyibike.uu.utils.PhoneUtils;
import com.zhouyibike.uu.utils.TextUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class SplashActivity extends BaseActivity {

    private final int SDK_PERMISSION_REQUEST = 127;
    private Dialog updialog;
    private boolean isshowupdialog;
    private boolean isqqok, istimeok;
    private int time = 2;
    private MyHandler myHandler = new MyHandler();
    private Handler myHandler2 = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message message) {
            startActivity(new Intent(SplashActivity.this, MainActivity.class));
            finish();
            return false;
        }
    });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
//        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        EventBus.getDefault().register(this);
        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        int StatusBarH = PhoneUtils.getStatusBarHeight(this);
        Log.e("phone", "宽" + width + "高" + height + "状态栏高" + StatusBarH);
        DataSingle.getInstance().PhoneH = height;
        DataSingle.getInstance().PhoneW = width;
        DataSingle.getInstance().StatusBarH = StatusBarH;
        getPersimmions();
        myHandler.sendEmptyMessage(1);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP)//5.0
        {
//            Build.VERSION_CODES.LOLLIPOP
        } else {
            ImmersionBar.with(this)
                    .transparentStatusBar()  //透明状态栏，不写默认透明色
                    //  .transparentNavigationBar()  //透明导航栏，不写默认黑色(设置此方法，fullScreen()方法自动为true)
                    //   .transparentBar()             //透明状态栏和导航栏，不写默认状态栏为透明色，导航栏为黑色（设置此方法，fullScreen()方法自动为true）
//                    .statusBarColor(R.color.bg_main_white)     //状态栏颜色，不写默认透明色
                    //  .navigationBarColor(R.color.colorPrimary) //导航栏颜色，不写默认黑色
                    //   .barColor(R.color.colorPrimary)  //同时自定义状态栏和导航栏颜色，不写默认状态栏为透明色，导航栏为黑色
                    //  .statusBarAlpha(1f)  //状态栏透明度，不写默认0.0f
//                .navigationBarAlpha(0.4f)  //导航栏透明度，不写默认0.0F
//                .barAlpha(0.3f)  //状态栏和导航栏透明度，不写默认0.0f
                    .statusBarDarkFont(true)   //状态栏字体是深色，不写默认为亮色
                    //  .flymeOSStatusBarFontColor(R.color.btn3)  //修改flyme OS状态栏字体颜色
                    .fullScreen(false)      //有导航栏的情况下，activity全屏显示，也就是activity最下面被导航栏覆盖，不写默认非全屏
                    //   .hideBar(BarHide.FLAG_HIDE_BAR)  //隐藏状态栏或导航栏或两者，不写默认不隐藏
                    .fitsSystemWindows(false)    //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                    // .supportActionBar(true) //支持ActionBar使用
                    //  .statusBarColorTransform(R.color.orange)  //状态栏变色后的颜色
//                .navigationBarColorTransform(R.color.orange) //导航栏变色后的颜色
//                .barColorTransform(R.color.orange)  //状态栏和导航栏变色后的颜色
//                .removeSupportAllView() //移除全部view支持
                    .navigationBarEnable(true)   //是否可以修改导航栏颜色，默认为true
                    .navigationBarWithKitkatEnable(true)  //是否可以修改安卓4.4和emui3.1手机导航栏颜色，默认为true
                    .fixMarginAtBottom(true)   //已过时，当xml里使用android:fitsSystemWindows="true"属性时,解决4.4和emui3.1手机底部有时会出现多余空白的问题，默认为false，非必须
                    //  .reset()  //重置所以沉浸式参数
                    .keyboardEnable(false)  //解决软键盘与底部输入框冲突问题，默认为false，还有一个重载方法，可以指定软键盘mode
                    .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)  //单独指定软键盘模式
                    // .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED)  //单独指定软键盘模式
                    .setOnKeyboardListener(new OnKeyboardListener() {    //软键盘监听回调
                        @Override
                        public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
//                            LogUtils.e(isPopup);  //isPopup为true，软键盘弹出，为false，软键盘关闭
                        }
                    })
                    .init();  //必须调用方可沉浸式
        }
    }

    class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (time > 0) {
                time--;
                myHandler.sendEmptyMessageDelayed(1, 1000);
            } else {
                istimeok = true;
                getupmsg();
            }
        }
    }


    private void loadUpgradeInfo() {
        /***** 获取升级信息 *****/
        UpgradeInfo upgradeInfo = Beta.getUpgradeInfo();
        if (upgradeInfo == null) {
            if (istimeok) {
                startActivity(new Intent(SplashActivity.this, MainActivity.class));
                finish();
            } else {
                isqqok = true;
            }
            return;
        }
        if (getVersion() < upgradeInfo.versionCode) {
            Beta.checkUpgrade();
            isshowupdialog = true;
        } else {
            if (istimeok) {
                startActivity(new Intent(SplashActivity.this, MainActivity.class));
                finish();
            } else {
                isqqok = true;
            }
        }

    }

    private void getupmsg() {
        if (istimeok) {

        } else {
            return;
        }
        Map<String, String> params = new HashMap<>();
        addSubscription(apiStores.GetAndroidVersion(params),
                new ApiCallback<UpMSGResult>() {

                    @Override
                    public void onSuccess(final UpMSGResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            int lastev = 1;
                            String banbenname = "";
                            try {
                                //   lastev=Integer.parseInt(model.getData().getAppVersion());
                                banbenname = model.getData().getAppVersion();
                                //   toastShow(getVersionname().equals(banbenname)+"");
                                if (!getVersionname().equals(banbenname)) {
                                    DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
                                        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                                            if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                                                return true;
                                            } else {
                                                return false;
                                            }
                                        }
                                    };
                                    updialog = CustomerDialog.createVersionDialog(model.getData().isUpgrade(),SplashActivity.this, model.getData().getAppDescription(), new View.OnClickListener() {
                                        @Override
                                        public void onClick(View v) {
                                            switch (v.getId()) {
                                                case R.id.tv_versiondialog_cancle:
                                                    updialog.dismiss();
                                                    if (model.getData().isUpgrade()) {
                                                        finish();
                                                    } else {
                                                        startActivity(new Intent(SplashActivity.this, MainActivity.class));
                                                        finish();
                                                    }
                                                    break;
                                                case R.id.tv_versiondialog_update:
                                                    if(TextUtils.isNullorEmpty(model.getData().getAppDownLink()))
                                                    {
                                                        toastShow("更新失败,您可以通过应用宝或其他途径更新");
                                                    }else{
                                                        updialog.dismiss();
                                                        downloadApk(model.getData().getAppDownLink());
                                                    }

                                                    break;
                                            }
                                        }
                                    });
                                    updialog.setOnKeyListener(keylistener);
                                    updialog.show();
                                } else {
//                                    startActivity(new Intent(SplashActivity.this,MainActivity.class));
//                                    finish();
                                    myHandler2.sendEmptyMessageDelayed(0, 1000);
                                }
                            } catch (Exception e) {
                                myHandler2.sendEmptyMessageDelayed(0, 1000);
                            }
                        } else {
                            startActivity(new Intent(SplashActivity.this, MainActivity.class));
                            finish();
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        startActivity(new Intent(SplashActivity.this, MainActivity.class));
                        finish();
                    }

                    @Override
                    public void onFinish() {
                    }
                });

//        if(isshowupdialog){
//            startActivity(new Intent(SplashActivity.this,MainActivity.class));
//            finish();
//        }else {
//            loadUpgradeInfo();
//        }
//
        /*
        PgyUpdateManager.register(this, "provider_paths",
        new UpdateManagerListener() {

            @Override
            public void onUpdateAvailable(final String result) {

                // 将新版本信息封装到AppBean中
                final AppBean appBean = getAppBeanFromString(result);
                updialog= CustomerDialog.createVersionDialog(SplashActivity.this, appBean.getReleaseNote(), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        switch (v.getId()){
                            case R.id.tv_versiondialog_cancle:
                                updialog.dismiss();
                                startActivity(new Intent(SplashActivity.this,MainActivity.class));
                                finish();
                                break;
                            case R.id.tv_versiondialog_update:
                                updialog.dismiss();
                                downloadApk(appBean.getDownloadURL());
                                break;
                        }
                    }
                });
                updialog.show();
            }

            @Override
            public void onNoUpdateAvailable() {
                startActivity(new Intent(SplashActivity.this,MainActivity.class));
                finish();
            }
        });
        */
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public int getVersion() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;

            return info.versionCode;
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 获取版本号
     *
     * @return 当前应用的版本号
     */
    public String getVersionname() {
        try {
            PackageManager manager = this.getPackageManager();
            PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0);
            String version = info.versionName;

            return version;
        } catch (Exception e) {
            return "";
        }
    }

    ProgressDialog mProgress;

    public void downloadApk(String url) {
        Intent intent = new Intent(this, UpdateService.class);
        intent.putExtra("download_url", url);
        mProgress = createProgressDialog();
        mProgress.show();
        startService(intent);
    }

    private ProgressDialog createProgressDialog() {
        DialogInterface.OnKeyListener keylistener = new DialogInterface.OnKeyListener() {
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                    return true;
                } else {
                    return false;
                }
            }
        };
        ProgressDialog mProgress = new ProgressDialog(this);
        mProgress.setIcon(R.mipmap.ic_launcher);
        mProgress.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
        mProgress.setCancelable(true);
        mProgress.setOnKeyListener(keylistener);
        mProgress.setTitle("升级中");
        mProgress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
//        mProgress.setButton("后台下载",new SureButtonListener());
        return mProgress;
    }

    //Dialog中确定按钮的监听器
    private class SureButtonListener implements android.content.DialogInterface.OnClickListener {

        public void onClick(DialogInterface dialog, int which) {
            //点击“确定按钮”取消对话框
            dialog.cancel();
            startActivity(new Intent(SplashActivity.this, MainActivity.class));
            finish();
        }

    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void getProgress(Integer progress) {
        if (progress > 0) {
            mProgress.setProgress(progress);
            Log.e("tag12", "getProgress: " + progress);
            if (progress >= 100) {
                mProgress.dismiss();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @TargetApi(23)
    private void getPersimmions() {
//        PermissionUtils.isCameraPermission(MainActivity.this, 0x007);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.CAMERA);
            }
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.BLUETOOTH);
            }
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_ADMIN) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.BLUETOOTH_ADMIN);
            }
            if (permissions.size() > 0) {
                ActivityCompat.requestPermissions(this, permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            } else {
                if (dialog != null && dialog.isShowing()) {
                    dialog.dismiss();
                }
                getupmsg();
            }
        } else {
            getupmsg();
        }
    }


    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case SDK_PERMISSION_REQUEST:
                for (int i = 0; i < grantResults.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                        }
                    } else {
                        if (dialog == null || !dialog.isShowing())
                            showMissingPermissionDialog();
                    }
                }
                break;
        }
    }

    private Dialog dialog;

    // 显示缺失权限提示
    private void showMissingPermissionDialog() {
        dialog = CustomerDialog.createDeletaDialog(this, "是否添加权限？", new MyOnclicklistener());
        dialog.show();
    }

    class MyOnclicklistener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.tv_deletedialog_cancle:
                    finish();
                    break;
                case R.id.tv_deletedialog_delete:
                    dialog.dismiss();
                    startAppSettings();
                    break;
            }
        }
    }

    // 启动应用的设置
    private void startAppSettings() {
        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.parse("package:" + getPackageName()));
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
